$(function () {
	let timer
	let user = JSON.parse(getLocalStorage('user')) || JSON.parse(getSession('user'))
	let sid
	if (user && user.sid) {
		sid = user.sid
	}
	let num = 1
	/**
	 * 未登录跳转的登录页面
	 */
	if (!sid) login('/weixin/login.html')
	/**
	 * 请求站点数和设备数
	 */
	post({
		url: '/Site/UserSite',
		data: {
			userId: sid
		},
		success: (data) => {
			if (data != null) {
				$('.count').text(data.count)
				$('.point').text(data.point)
			}
		}
	})
	/**
	 * 请求报警列表
	 */
	post({
		url: '/Site/Police',
		data: {
			userId: sid
		},
		success: (data) => {
			if (data != null) {
				$.each(data, (index, item) => {
					appendTr(item)
				})
			}
		}
	})
	/**
	 * 给表单注册事件并弹出提示, 3秒后隐藏
	 */
	$('.table tbody').on('click', 'tr', (e) => {
		if (timer) clearTimeout(timer)
		e = e.target || window.Event || e.srcElement
		let tds = $(e).parent().find('td')
		let str, zhan, she, dian, time
		tds.each((index, item) => {
			switch (index) {
				case 1:
					zhan = $(item).text()
					break
				case 3:
					she = $(item).text()
					break
				case 4:
					dian = $(item).text()
					break
				case 5:
					time = $(item).text()
					break
			}
		})
		str = zhan + '站' + she + '设备' + dian + '点位与' + time + '报警'
		let moveTop = e.offsetTop - $('.list').scrollTop() + e.clientHeight / 2
		$('.move').show().text(str).css({
			top: moveTop
		})
		timer = setTimeout(() => {
			$('.move').hide()
		}, 3000)
	})
	function appendTr(obj) {
		$('.table tbody').append(`<tr> <td>${num++}</td> <td>${obj.siteName}</td> <td>${obj.voltage}</td> <td>${obj.name}</td> <td>${obj.point}</td> <td>${new Date(obj.createtime).format('YYYY-MM-DD HH:mm:ss')}</td> </tr>`)
	}
	/**
	 * 给导航按钮注册事件
	 */
	$('.links').on('click', 'a', (e) => {
		e = e.target || window.Event || e.srcElement
		setLocalStorage('devType', $(e).data('type'))
	})
	/**
	 * 节流, 让 function 延长一段时间执行
	 * @param {function} fn 延长执行的 function
	 * @param {number} wait 延长执行的时间
	 * @returns {function}
	 */
	function debounce(fn, wait) {
		let timeout = null
		return function () {
			if (timeout !== null) clearTimeout(timeout)
			timeout = setTimeout(fn, wait)
		}
	}
	/**
	 * 延迟一定的时间执行的函数, scroll 事件, 判断是否触底, 如触底则执行固定表头并加载元素
	 */
	function handle() {
		let listHeight = $('.list').scrollTop()
		let tbodyHeight = $('.list tbody').outerHeight(true)
		let outerHeight = $('.list').outerHeight(true)
		$('.table thead tr').css({ 'transform': 'translate(0, ' + listHeight + 'px)', 'backgroundColor': '#202025' })
		/* 
		 if (listHeight + outerHeight > tbodyHeight - outerHeight) {
			for (var i = num; i < (num + 20); i++) {
				appendTr({
					num: i
				})
			}
			num = i
		}
		*/
	}
	//handle()
	$('.list').on('scroll', debounce(handle, 1000))
})